<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMCPTemplateController extends DMCPAdminController {

	public function add() {
		$this->preFlightCheck();
		$ts = new DMTemplateSet();
		$ts->setName("New Template Set");

		$form = new DMCPTemplateSetForm($ts);
		$this->setForm($form);

		if (DMHTTPRequest::getCurrent()->getMethod() == DMHTTPMethod::POST) {
			$this->handleForm(null, "admin/templates");
		}

		$this->initAddEditTemplate($ts);
	}

	private function delete() {
		$this->preFlightCheck();
		$rep = DMHTTPRequest::getCurrent()->getRepresentation();
		if ($rep->getFormValue("id")) {
			try {
				$tpl = new DMTemplateSet($rep->getFormValue("id"));
				$tpl->delete();
				DMHTTPRequest::getCurrent()->getSession()->setFlash(new DMFlash(
						DMLocalizedString::getString("TEMPLATE_SET_DELETED"),
						true));
			} catch (DMException $e) {
				DMHTTPRequest::getCurrent()->getSession()->setFlash(
						new DMFlash($e->getMessage(), false));
			}
		}
	}

	public function edit($id) {
		$this->preFlightCheck();
		$id = (int) $id;
		$ts = new DMTemplateSet($id);

		$form = new DMCPTemplateSetForm($ts);
		$this->setForm($form);

		if (DMHTTPRequest::getCurrent()->getMethod() == DMHTTPMethod::POST) {
			$this->handleForm(
					DMLocalizedString::getString("TEMPLATE_SET_UPDATED"),
					"admin/templates");
		}

		$this->initAddEditTemplate($ts);
	}

	private function initAddEditTemplate(DMTemplateSet $ts) {
		$form = $this->getForm();
		try {
			// template set info
			$this->tpl_vars['template_set'] = $ts;
			$this->tpl_vars['all_collections'] = array_merge(
					array(DMCollectionFactory::getCollection("/dmdefault")),
					DMCollection::getAuthorized());
			foreach ($form->getFieldsByName("allowed_collections") as $field) {
				$this->tpl_vars['allowed_collections'][] = $field->getHTMLTag();
			}
			foreach ($form->getFieldsByName("default_collection") as $field) {
				$this->tpl_vars['default_collection'][] = $field->getHTMLTag();
			}
			$this->tpl_vars['name'] = $form->getFieldByName("name")->getHTMLTag();

			// results per page
			$this->tpl_vars['results_per_page']
					= $form->getFieldByName("results_per_page")->getHTMLTag();

			// tile view
			$this->tpl_vars['tile_cols'] = $form
					->getFieldByName("tile_cols")->getHTMLTag();
		} catch (DMException $e) {
			DMHTTPRequest::getCurrent()->getSession()->setFlash(
					new DMFlash($e->getMessage(), false));
		}

		$this->renderTemplate("/templates/template/edit.html.php");
		die;
	}

	public function index() {
		$this->preFlightCheck();

		if (DMHTTPRequest::getCurrent()->getMethod() == DMHTTPMethod::POST) {
			$this->delete();
		}

		$this->renderTemplate("/templates/template/index.html.php");
		die;
	}

}

